package com.jingjing.control.common;

import com.alibaba.fastjson.JSONObject;
import com.jingjing.model.user.User;
import com.jingjing.service.note.NoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @program: jingjing
 * @description: 通过控制器
 * @author: 何伟
 * @create: 2019-06-04 17:29
 **/
@Controller
@RequestMapping("common")
public class CommonController {

    @Autowired
    private NoteService noteService;

    private Logger logger= LoggerFactory.getLogger(this.getClass());
    @RequestMapping("/uploadImg")
    public void uploadPic(@RequestParam("file") MultipartFile file,Long noteid, HttpServletResponse response, HttpSession session) throws Exception {

        JSONObject jsonObject = new JSONObject();
        User user = (User) session.getAttribute("user");
        // 图片上传的相对路径（因为相对路径放到页面上就可以显示图片）
        String webPath = session.getServletContext().getRealPath("");
        String path = webPath + "WEB-INF"+File.separator+"classes"+File.separator+"static"+File.separator+"upload" + File.separator+"image" +File.separator + user.getId() + File.separator;
//            String path = File.separator + "img" + File.separator + name + "_" + originalFilename;

        jsonObject=uploadFile(path,file);

        if (jsonObject.getString("path")!=null||jsonObject.getString("path")!=""){
            noteService.updateImgcover(noteid,jsonObject.getString("path"));
        }

        // 设置响应数据的类型json
        response.setContentType("application/json; charset=utf-8");
        response.getWriter().write(jsonObject.toString());

    }

    public JSONObject uploadFile(String path,MultipartFile file) throws Exception{
        JSONObject jsonObject = new JSONObject();
        try {

            // 文件名使用当前时间
//            String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
            // 获取图片原始文件名
            String originalFilename = file.getOriginalFilename();

            String fileName=originalFilename.substring(0,originalFilename.lastIndexOf("."));

            String ct = file.getContentType() ;
            String fileType = "";
            if (ct.indexOf("/")>0) {
                fileType = ct.substring(ct.indexOf("/")+1);
            }

            logger.info("上传文件路径："+path);
            logger.info("上传文件格式："+fileType);
            logger.info("上传文件名称："+fileName);

            // 图片上传的绝对路径
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            File targetFile = new File(path+File.separator+fileName+"."+fileType);
            if (!targetFile.exists()) {
                targetFile.createNewFile();
            }
            // 上传图片
            file.transferTo(targetFile);
            // 将相对路径写回（json格式）

            jsonObject.put("path", path.substring(path.indexOf("static"))+File.separator+fileName+"."+fileType);

        } catch (Exception e) {
            //throw new RuntimeException("服务器繁忙，上传图片失败");
            jsonObject.put("errorMsg", "文件上传失败！");
            logger.error(e.getMessage());
        }
        return jsonObject;
    }
}

